/*
 * Copyright (c) 2000-2001,2005 Silicon Graphics, Inc.
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it would be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write the Free Software Foundation,
 * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
#ifndef __DFS_BTREE_H__
#define	__DFS_BTREE_H__

struct dfs_buf;
struct dfs_bmap_free;
struct dfs_inode;
struct dfs_mount;
struct dfs_trans;

extern kmem_zone_t	*dfs_btree_cur_zone;

/*
 * Generic key, ptr and record wrapper structures.
 *
 * These are disk format structures, and are converted where necessary
 * by the btree specific code that needs to interpret them.
 */
union dfs_btree_ptr {
	__be32			s;	/* short form ptr */
	__be64			l;	/* long form ptr */
};

union dfs_btree_key {
	dfs_bmbt_key_t		bmbt;
	dfs_bmdr_key_t		bmbr;	/* bmbt root block */
	dfs_alloc_key_t		alloc;
	dfs_inobt_key_t		inobt;
};

union dfs_btree_rec {
	dfs_bmbt_rec_t		bmbt;
	dfs_bmdr_rec_t		bmbr;	/* bmbt root block */
	dfs_alloc_rec_t		alloc;
	dfs_inobt_rec_t		inobt;
};

/*
 * This nonsense is to make -wlint happy.
 */
#define	DFS_LOOKUP_EQ	((dfs_lookup_t)DFS_LOOKUP_EQi)
#define	DFS_LOOKUP_LE	((dfs_lookup_t)DFS_LOOKUP_LEi)
#define	DFS_LOOKUP_GE	((dfs_lookup_t)DFS_LOOKUP_GEi)

#define	DFS_BTNUM_BNO	((dfs_btnum_t)DFS_BTNUM_BNOi)
#define	DFS_BTNUM_CNT	((dfs_btnum_t)DFS_BTNUM_CNTi)
#define	DFS_BTNUM_BMAP	((dfs_btnum_t)DFS_BTNUM_BMAPi)
#define	DFS_BTNUM_INO	((dfs_btnum_t)DFS_BTNUM_INOi)

/*
 * For logging record fields.
 */
#define	DFS_BB_MAGIC		(1 << 0)
#define	DFS_BB_LEVEL		(1 << 1)
#define	DFS_BB_NUMRECS		(1 << 2)
#define	DFS_BB_LEFTSIB		(1 << 3)
#define	DFS_BB_RIGHTSIB		(1 << 4)
#define	DFS_BB_BLKNO		(1 << 5)
#define	DFS_BB_LSN		(1 << 6)
#define	DFS_BB_UUID		(1 << 7)
#define	DFS_BB_OWNER		(1 << 8)
#define	DFS_BB_NUM_BITS		5
#define	DFS_BB_ALL_BITS		((1 << DFS_BB_NUM_BITS) - 1)
#define	DFS_BB_NUM_BITS_CRC	9
#define	DFS_BB_ALL_BITS_CRC	((1 << DFS_BB_NUM_BITS_CRC) - 1)

/*
 * Generic stats interface
 */
#define __DFS_BTREE_STATS_INC(type, stat) \
	DFS_STATS_INC(xs_ ## type ## _2_ ## stat)
#define DFS_BTREE_STATS_INC(cur, stat)  \
do {    \
	switch (cur->bc_btnum) {  \
	case DFS_BTNUM_BNO: __DFS_BTREE_STATS_INC(abtb, stat); break;	\
	case DFS_BTNUM_CNT: __DFS_BTREE_STATS_INC(abtc, stat); break;	\
	case DFS_BTNUM_BMAP: __DFS_BTREE_STATS_INC(bmbt, stat); break;	\
	case DFS_BTNUM_INO: __DFS_BTREE_STATS_INC(ibt, stat); break;	\
	case DFS_BTNUM_MAX: ASSERT(0); /* fucking gcc */ ; break;	\
	}       \
} while (0)

#define __DFS_BTREE_STATS_ADD(type, stat, val) \
	DFS_STATS_ADD(xs_ ## type ## _2_ ## stat, val)
#define DFS_BTREE_STATS_ADD(cur, stat, val)  \
do {    \
	switch (cur->bc_btnum) {  \
	case DFS_BTNUM_BNO: __DFS_BTREE_STATS_ADD(abtb, stat, val); break; \
	case DFS_BTNUM_CNT: __DFS_BTREE_STATS_ADD(abtc, stat, val); break; \
	case DFS_BTNUM_BMAP: __DFS_BTREE_STATS_ADD(bmbt, stat, val); break; \
	case DFS_BTNUM_INO: __DFS_BTREE_STATS_ADD(ibt, stat, val); break; \
	case DFS_BTNUM_MAX: ASSERT(0); /* fucking gcc */ ; break;	\
	}       \
} while (0)

#define	DFS_BTREE_MAXLEVELS	8	/* max of all btrees */

struct dfs_btree_ops {
	/* size of the key and record structures */
	size_t	key_len;
	size_t	rec_len;

	/* cursor operations */
	struct dfs_btree_cur *(*dup_cursor)(struct dfs_btree_cur *);
	void	(*update_cursor)(struct dfs_btree_cur *src,
				 struct dfs_btree_cur *dst);

	/* update btree root pointer */
	void	(*set_root)(struct dfs_btree_cur *cur,
			    union dfs_btree_ptr *nptr, int level_change);

	/* block allocation / freeing */
	int	(*alloc_block)(struct dfs_btree_cur *cur,
			       union dfs_btree_ptr *start_bno,
			       union dfs_btree_ptr *new_bno,
			       int length, int *stat);
	int	(*free_block)(struct dfs_btree_cur *cur, struct dfs_buf *bp);

	/* update last record information */
	void	(*update_lastrec)(struct dfs_btree_cur *cur,
				  struct dfs_btree_block *block,
				  union dfs_btree_rec *rec,
				  int ptr, int reason);

	/* records in block/level */
	int	(*get_minrecs)(struct dfs_btree_cur *cur, int level);
	int	(*get_maxrecs)(struct dfs_btree_cur *cur, int level);

	/* records on disk.  Matter for the root in inode case. */
	int	(*get_dmaxrecs)(struct dfs_btree_cur *cur, int level);

	/* init values of btree structures */
	void	(*init_key_from_rec)(union dfs_btree_key *key,
				     union dfs_btree_rec *rec);
	void	(*init_rec_from_key)(union dfs_btree_key *key,
				     union dfs_btree_rec *rec);
	void	(*init_rec_from_cur)(struct dfs_btree_cur *cur,
				     union dfs_btree_rec *rec);
	void	(*init_ptr_from_cur)(struct dfs_btree_cur *cur,
				     union dfs_btree_ptr *ptr);

	/* difference between key value and cursor value */
	__int64_t (*key_diff)(struct dfs_btree_cur *cur,
			      union dfs_btree_key *key);

	const struct dfs_buf_ops	*buf_ops;

#if defined(DEBUG) || defined(DFS_WARN)
	/* check that k1 is lower than k2 */
	int	(*keys_inorder)(struct dfs_btree_cur *cur,
				union dfs_btree_key *k1,
				union dfs_btree_key *k2);

	/* check that r1 is lower than r2 */
	int	(*recs_inorder)(struct dfs_btree_cur *cur,
				union dfs_btree_rec *r1,
				union dfs_btree_rec *r2);
#endif
};

/*
 * Reasons for the update_lastrec method to be called.
 */
#define LASTREC_UPDATE	0
#define LASTREC_INSREC	1
#define LASTREC_DELREC	2


/*
 * Btree cursor structure.
 * This collects all information needed by the btree code in one place.
 */
typedef struct dfs_btree_cur
{
	struct dfs_trans	*bc_tp;	/* transaction we're in, if any */
	struct dfs_mount	*bc_mp;	/* file system mount struct */
	const struct dfs_btree_ops *bc_ops;
	uint			bc_flags; /* btree features - below */
	union {
		dfs_alloc_rec_incore_t	a;
		dfs_bmbt_irec_t		b;
		dfs_inobt_rec_incore_t	i;
	}		bc_rec;		/* current insert/search record value */
	struct dfs_buf	*bc_bufs[DFS_BTREE_MAXLEVELS];	/* buf ptr per level */
	int		bc_ptrs[DFS_BTREE_MAXLEVELS];	/* key/record # */
	__uint8_t	bc_ra[DFS_BTREE_MAXLEVELS];	/* readahead bits */
#define	DFS_BTCUR_LEFTRA	1	/* left sibling has been read-ahead */
#define	DFS_BTCUR_RIGHTRA	2	/* right sibling has been read-ahead */
	__uint8_t	bc_nlevels;	/* number of levels in the tree */
	__uint8_t	bc_blocklog;	/* log2(blocksize) of btree blocks */
	dfs_btnum_t	bc_btnum;	/* identifies which btree type */
	union {
		struct {			/* needed for BNO, CNT, INO */
			struct dfs_buf	*agbp;	/* agf/agi buffer pointer */
			dfs_agnumber_t	agno;	/* ag number */
		} a;
		struct {			/* needed for BMAP */
			struct dfs_inode *ip;	/* pointer to our inode */
			struct dfs_bmap_free *flist;	/* list to free after */
			dfs_fsblock_t	firstblock;	/* 1st blk allocated */
			int		allocated;	/* count of alloced */
			short		forksize;	/* fork's inode space */
			char		whichfork;	/* data or attr fork */
			char		flags;		/* flags */
#define	DFS_BTCUR_BPRV_WASDEL	1			/* was delayed */
		} b;
	}		bc_private;	/* per-btree type data */
} dfs_btree_cur_t;

/* cursor flags */
#define DFS_BTREE_LONG_PTRS		(1<<0)	/* pointers are 64bits long */
#define DFS_BTREE_ROOT_IN_INODE		(1<<1)	/* root may be variable size */
#define DFS_BTREE_LASTREC_UPDATE	(1<<2)	/* track last rec externally */
#define DFS_BTREE_CRC_BLOCKS		(1<<3)	/* uses extended btree blocks */


#define	DFS_BTREE_NOERROR	0
#define	DFS_BTREE_ERROR		1

/*
 * Convert from buffer to btree block header.
 */
#define	DFS_BUF_TO_BLOCK(bp)	((struct dfs_btree_block *)((bp)->b_addr))


/*
 * Check that block header is ok.
 */
int
dfs_btree_check_block(
	struct dfs_btree_cur	*cur,	/* btree cursor */
	struct dfs_btree_block	*block,	/* generic btree block pointer */
	int			level,	/* level of the btree block */
	struct dfs_buf		*bp);	/* buffer containing block, if any */

/*
 * Check that (long) pointer is ok.
 */
int					/* error (0 or EFSCORRUPTED) */
dfs_btree_check_lptr(
	struct dfs_btree_cur	*cur,	/* btree cursor */
	dfs_dfsbno_t		ptr,	/* btree block disk address */
	int			level);	/* btree block level */

/*
 * Delete the btree cursor.
 */
void
dfs_btree_del_cursor(
	dfs_btree_cur_t		*cur,	/* btree cursor */
	int			error);	/* del because of error */

/*
 * Duplicate the btree cursor.
 * Allocate a new one, copy the record, re-get the buffers.
 */
int					/* error */
dfs_btree_dup_cursor(
	dfs_btree_cur_t		*cur,	/* input cursor */
	dfs_btree_cur_t		**ncur);/* output cursor */

/*
 * Get a buffer for the block, return it with no data read.
 * Long-form addressing.
 */
struct dfs_buf *				/* buffer for fsbno */
dfs_btree_get_bufl(
	struct dfs_mount	*mp,	/* file system mount point */
	struct dfs_trans	*tp,	/* transaction pointer */
	dfs_fsblock_t		fsbno,	/* file system block number */
	uint			lock);	/* lock flags for get_buf */

/*
 * Get a buffer for the block, return it with no data read.
 * Short-form addressing.
 */
struct dfs_buf *				/* buffer for agno/agbno */
dfs_btree_get_bufs(
	struct dfs_mount	*mp,	/* file system mount point */
	struct dfs_trans	*tp,	/* transaction pointer */
	dfs_agnumber_t		agno,	/* allocation group number */
	dfs_agblock_t		agbno,	/* allocation group block number */
	uint			lock);	/* lock flags for get_buf */

/*
 * Check for the cursor referring to the last block at the given level.
 */
int					/* 1=is last block, 0=not last block */
dfs_btree_islastblock(
	dfs_btree_cur_t		*cur,	/* btree cursor */
	int			level);	/* level to check */

/*
 * Compute first and last byte offsets for the fields given.
 * Interprets the offsets table, which contains struct field offsets.
 */
void
dfs_btree_offsets(
	__int64_t		fields,	/* bitmask of fields */
	const short		*offsets,/* table of field offsets */
	int			nbits,	/* number of bits to inspect */
	int			*first,	/* output: first byte offset */
	int			*last);	/* output: last byte offset */

/*
 * Get a buffer for the block, return it read in.
 * Long-form addressing.
 */
int					/* error */
dfs_btree_read_bufl(
	struct dfs_mount	*mp,	/* file system mount point */
	struct dfs_trans	*tp,	/* transaction pointer */
	dfs_fsblock_t		fsbno,	/* file system block number */
	uint			lock,	/* lock flags for read_buf */
	struct dfs_buf		**bpp,	/* buffer for fsbno */
	int			refval,	/* ref count value for buffer */
	const struct dfs_buf_ops *ops);

/*
 * Read-ahead the block, don't wait for it, don't return a buffer.
 * Long-form addressing.
 */
void					/* error */
dfs_btree_reada_bufl(
	struct dfs_mount	*mp,	/* file system mount point */
	dfs_fsblock_t		fsbno,	/* file system block number */
	dfs_extlen_t		count,	/* count of filesystem blocks */
	const struct dfs_buf_ops *ops);

/*
 * Read-ahead the block, don't wait for it, don't return a buffer.
 * Short-form addressing.
 */
void					/* error */
dfs_btree_reada_bufs(
	struct dfs_mount	*mp,	/* file system mount point */
	dfs_agnumber_t		agno,	/* allocation group number */
	dfs_agblock_t		agbno,	/* allocation group block number */
	dfs_extlen_t		count,	/* count of filesystem blocks */
	const struct dfs_buf_ops *ops);

/*
 * Initialise a new btree block header
 */
void
dfs_btree_init_block(
	struct dfs_mount *mp,
	struct dfs_buf	*bp,
	__u32		magic,
	__u16		level,
	__u16		numrecs,
	__u64		owner,
	unsigned int	flags);

void
dfs_btree_init_block_int(
	struct dfs_mount	*mp,
	struct dfs_btree_block	*buf,
	dfs_daddr_t		blkno,
	__u32			magic,
	__u16			level,
	__u16			numrecs,
	__u64			owner,
	unsigned int		flags);

/*
 * Common btree core entry points.
 */
int dfs_btree_increment(struct dfs_btree_cur *, int, int *);
int dfs_btree_decrement(struct dfs_btree_cur *, int, int *);
int dfs_btree_lookup(struct dfs_btree_cur *, dfs_lookup_t, int *);
int dfs_btree_update(struct dfs_btree_cur *, union dfs_btree_rec *);
int dfs_btree_new_iroot(struct dfs_btree_cur *, int *, int *);
int dfs_btree_insert(struct dfs_btree_cur *, int *);
int dfs_btree_delete(struct dfs_btree_cur *, int *);
int dfs_btree_get_rec(struct dfs_btree_cur *, union dfs_btree_rec **, int *);
int dfs_btree_change_owner(struct dfs_btree_cur *cur, __uint64_t new_owner,
			   struct list_head *buffer_list);

/*
 * btree block CRC helpers
 */
void dfs_btree_lblock_calc_crc(struct dfs_buf *);
bool dfs_btree_lblock_verify_crc(struct dfs_buf *);
void dfs_btree_sblock_calc_crc(struct dfs_buf *);
bool dfs_btree_sblock_verify_crc(struct dfs_buf *);

/*
 * Internal btree helpers also used by dfs_bmap.c.
 */
void dfs_btree_log_block(struct dfs_btree_cur *, struct dfs_buf *, int);
void dfs_btree_log_recs(struct dfs_btree_cur *, struct dfs_buf *, int, int);

/*
 * Helpers.
 */
static inline int dfs_btree_get_numrecs(struct dfs_btree_block *block)
{
	return be16_to_cpu(block->bb_numrecs);
}

static inline void dfs_btree_set_numrecs(struct dfs_btree_block *block,
		__uint16_t numrecs)
{
	block->bb_numrecs = cpu_to_be16(numrecs);
}

static inline int dfs_btree_get_level(struct dfs_btree_block *block)
{
	return be16_to_cpu(block->bb_level);
}


/*
 * Min and max functions for extlen, agblock, fileoff, and filblks types.
 */
#define	DFS_EXTLEN_MIN(a,b)	min_t(dfs_extlen_t, (a), (b))
#define	DFS_EXTLEN_MAX(a,b)	max_t(dfs_extlen_t, (a), (b))
#define	DFS_AGBLOCK_MIN(a,b)	min_t(dfs_agblock_t, (a), (b))
#define	DFS_AGBLOCK_MAX(a,b)	max_t(dfs_agblock_t, (a), (b))
#define	DFS_FILEOFF_MIN(a,b)	min_t(dfs_fileoff_t, (a), (b))
#define	DFS_FILEOFF_MAX(a,b)	max_t(dfs_fileoff_t, (a), (b))
#define	DFS_FILBLKS_MIN(a,b)	min_t(dfs_filblks_t, (a), (b))
#define	DFS_FILBLKS_MAX(a,b)	max_t(dfs_filblks_t, (a), (b))

#define	DFS_FSB_SANITY_CHECK(mp,fsb)	\
	(DFS_FSB_TO_AGNO(mp, fsb) < mp->m_sb.sb_agcount && \
		DFS_FSB_TO_AGBNO(mp, fsb) < mp->m_sb.sb_agblocks)

/*
 * Trace hooks.  Currently not implemented as they need to be ported
 * over to the generic tracing functionality, which is some effort.
 *
 * i,j = integer (32 bit)
 * b = btree block buffer (dfs_buf_t)
 * p = btree ptr
 * r = btree record
 * k = btree key
 */
#define	DFS_BTREE_TRACE_ARGBI(c, b, i)
#define	DFS_BTREE_TRACE_ARGBII(c, b, i, j)
#define	DFS_BTREE_TRACE_ARGI(c, i)
#define	DFS_BTREE_TRACE_ARGIPK(c, i, p, s)
#define	DFS_BTREE_TRACE_ARGIPR(c, i, p, r)
#define	DFS_BTREE_TRACE_ARGIK(c, i, k)
#define DFS_BTREE_TRACE_ARGR(c, r)
#define	DFS_BTREE_TRACE_CURSOR(c, t)

#endif	/* __DFS_BTREE_H__ */
